package com.zdsoft.blp.zongbuju.shouye.taoshihui.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.zdsoft.blp.R;
import com.zdsoft.blp.gongyong.API.API;
import com.zdsoft.blp.gongyong.fanhui.FanHuiView;
import com.zdsoft.blp.gongyong.net.BaseActivity;
import com.zdsoft.blp.gongyong.net.Net;
import com.zdsoft.blp.gongyong.net.NetCallback;
import com.zdsoft.blp.zongbuju.shouye.taoshihui.entity.Address;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by pc on 2016/9/9.
 */
public class XiuGaiAddressActivity extends BaseActivity implements View.OnClickListener, NetCallback {
    private FanHuiView fh;
    private RelativeLayout rl_delete;
    private ImageView iv_delete;
    private TextView tv_baocun, et_xxaddress, et_name, et_phone;
    private CheckBox cb_moren;
    private Spinner sp;
    private String jieDao = null, id = null;
    private static final int ADDRESSSAVE = 1;
    private static final int ADDRESSREMOVE = 2;
    private PopupWindow popupWindow;
    @Override
    protected void init() {
        setContentView(R.layout.tsh_address);

        fh = find(R.id.fh);
        rl_delete = find(R.id.rl_delete);
        iv_delete = find(R.id.iv_delete);
        tv_baocun = find(R.id.tv_baocun);
        tv_baocun = find(R.id.tv_baocun);
        sp = find(R.id.sp);
        et_xxaddress = find(R.id.et_xxaddress);
        et_name = find(R.id.et_name);
        et_phone = find(R.id.et_phone);
        cb_moren = find(R.id.cb_moren);

        fh.getTv_title().setText("修改收货地址");
        rl_delete.setVisibility(View.VISIBLE);
        final String[] mItems = getResources().getStringArray(R.array.qu);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mItems);
        adapter.setDropDownViewResource(android.R.layout.select_dialog_singlechoice);
        sp.setAdapter(adapter);
        sp.setPrompt("请选择城市");
        sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                jieDao = mItems[position];
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        Bundle bundle = getIntent().getExtras();
        Address address = (Address) bundle.get("address");
        et_xxaddress.setText(address.getXiangxi());
        et_name.setText(address.getName());
        et_phone.setText(address.getDianhua());
        cb_moren.setChecked("Y".equals(address.getMoren()));
        id = address.getId();

        iv_delete.setOnClickListener(this);
        tv_baocun.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_delete:
                getPopupWindow();
                backgroundAlpha();
                // 这里是位置显示方式,在屏幕的上侧
                popupWindow.showAtLocation(iv_delete, Gravity.CENTER,0,0);
                break;
            case R.id.tv_baocun:
                String xxaddress = et_xxaddress.getText().toString();
                String name = et_name.getText().toString();
                String phone = et_phone.getText().toString();
                if ("".equals(jieDao)) {
                    Toast.makeText(getApplicationContext(), "街道不能为空", Toast.LENGTH_SHORT).show();
                } else if ("".equals(xxaddress)) {
                    Toast.makeText(getApplicationContext(), "详细地址不能为空", Toast.LENGTH_SHORT).show();
                } else if ("".equals(name)) {
                    Toast.makeText(getApplicationContext(), "姓名不能为空", Toast.LENGTH_SHORT).show();
                } else if ("".equals(phone)) {
                    Toast.makeText(getApplicationContext(), "电话不能为空", Toast.LENGTH_SHORT).show();
                } else {
                    baoCunData(name, xxaddress, phone);
                }
                break;
        }

    }

    private void deleteData() {
        Net net = new Net();
        net.url = API.ADDRESS_URL;
        net.nameSpace = API.ADDRESS_NAMESPACE;
        net.methodName = API.ADDRESSREMOVE;
        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        net.parms = map;
        net.code = ADDRESSREMOVE;
        getServer(net, XiuGaiAddressActivity.this);
    }

    private void baoCunData(String name, String xxaddress, String phone) {
        SharedPreferences sp = XiuGaiAddressActivity.this.getSharedPreferences("info", Context.MODE_PRIVATE);
        String userId = sp.getString("userId", "");
        Net net = new Net();
        net.url = API.ADDRESS_URL;
        net.nameSpace = API.ADDRESS_NAMESPACE;
        net.methodName = API.ADDRESSSAVE;
        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        map.put("xingming", name);
        map.put("dianhua", phone);
        map.put("guojia", "中国");
        map.put("sheng", "河南省");
        map.put("shi", "郑州市");
        map.put("qu", jieDao);
        map.put("xiangxi", xxaddress);
        map.put("youbian", "473000");
        if (cb_moren.isChecked()) {
            map.put("moren", "Y");
        } else {
            map.put("moren", "N");
        }
        map.put("userId", userId);
        net.parms = map;
        net.code = ADDRESSSAVE;
        getServer(net, XiuGaiAddressActivity.this);
    }

    @Override
    public void onResponse(boolean flag, int code, String res) {
        if (flag && code == ADDRESSSAVE) {
            try {
                JSONObject object = new JSONObject(res);
                if (object.getBoolean("result")) {
                    XiuGaiAddressActivity.this.finish();
                } else {
                    Toast.makeText(getApplicationContext(), object.getString("msg"), Toast.LENGTH_SHORT).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        if (flag && code == ADDRESSREMOVE) {
            try {
                JSONObject object = new JSONObject(res);
                if (object.getBoolean("result")) {
                    XiuGaiAddressActivity.this.finish();
                }
                Toast.makeText(getApplicationContext(), object.getString("msg"), Toast.LENGTH_SHORT).show();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }


    private void getPopupWindow() {
        if (null != popupWindow) {
            popupWindow.dismiss();
            return;
        } else {
            initPopuptWindow();
        }
    }

    protected void initPopuptWindow() {
        // TODO Auto-generated method stub
        // 获取自定义布局文件activity_popupwindow_left.xml的视图
        View popupWindow_view = getLayoutInflater().inflate(R.layout.tishiaddress, null, false);
        Button bt_queding = (Button) popupWindow_view.findViewById(R.id.bt_queding);
        Button bt_quxiao = (Button) popupWindow_view.findViewById(R.id.bt_quxiao);
        TextView tv_biaoti = (TextView) popupWindow_view.findViewById(R.id.tv_biaoti);
        tv_biaoti.setText("确定删除么");
        bt_quxiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dissmiss();
            }
        });
        bt_queding.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                deleteData();
                dissmiss();
            }
        });

        // 创建PopupWindow实例,200,LayoutParams.MATCH_PARENT分别是宽度和高度
        popupWindow = new PopupWindow(popupWindow_view, 900, 400, true);
        // 设置动画效果
        // popupWindow.setAnimationStyle(R.style.AnimationFade);
        // 点击其他地方消失
        /*popupWindow_view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // TODO Auto-generated method stub
                if (popupWindow != null && popupWindow.isShowing()) {
                    popupWindow.dismiss();
                    popupWindow = null;
                }
                return false;
            }
        });*/
    }

    public void backgroundAlpha() {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = (float) 0.5; //0.0-1.0
        getWindow().setAttributes(lp);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
    }

    public void dismissBackgroundAlpha() {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 1f; //0.0-1.0
        getWindow().setAttributes(lp);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
    }

    //让pop消失
    private void dissmiss() {
        popupWindow.dismiss();
        popupWindow = null;
        dismissBackgroundAlpha();
    }

}
